<template>
  <div class="room-list-container">
    <el-button type="primary" @click="refreshRooms" class="refresh-btn">
      刷新列表
    </el-button>
    
    <el-table :data="rooms" border stripe v-loading="loading">
      <el-table-column prop="room_name" label="会议室名称" width="180" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ row.type === 'classroom' ? '教室型' : '圆桌型' }}
        </template>
      </el-table-column>
      <el-table-column prop="area" label="面积(㎡)" width="100" />
      <el-table-column prop="seats" label="座位数" width="100" />
      <el-table-column prop="equipment" label="设备">
        <template #default="{ row }">
          <el-tag
            v-for="item in row.equipment"
            :key="item"
            size="small"
            class="mr-2"
          >
            {{ getEquipmentName(item) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格(元/小时)" width="120" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleBook(row)"
            :disabled="row.status !== 'idle'"
          >
            预订
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-dialog v-model="dialogVisible" title="预订会议室" width="500px">
      <el-form :model="bookingForm" label-width="100px">
        <el-form-item label="会议室">
          <el-input v-model="bookingForm.room_name" disabled />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="bookingForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
            :disabled-minutes="disabledMinutes"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="bookingForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
            :disabled-minutes="disabledMinutes"
          />
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="bookingForm.total_price" disabled>
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="bookingLoading">确认预订</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { filterRooms } from '@/api/rooms'
import { createOrder } from '@/api/orders'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const bookingLoading = ref(false)
const dialogVisible = ref(false)
const rooms = ref([])
const filterParams = ref({})

const bookingForm = ref({
  room_id: '',
  room_name: '',
  start_time: '',
  end_time: '',
  total_price: 0
})

const equipmentNames = {
  projector: '投影仪',
  audio: '音响',
  network: '网络',
  whiteboard: '白板',
  multimedia: '多媒体',
  stage: '舞台',
  video_conference: '视频会议',
  telephone: '电话'
}

const statusNames = {
  idle: '空闲',
  locked: '锁定',
  booked: '已预订',
  using: '使用中',
  maintenance: '维护中'
}

const statusTypes = {
  idle: 'success',
  locked: 'warning',
  booked: '',
  using: 'info',
  maintenance: 'danger'
}

// 初始化加载数据
onMounted(() => {
  if (route.query.rooms) {
    rooms.value = JSON.parse(route.query.rooms)
  }
  if (route.query.filterParams) {
    filterParams.value = JSON.parse(route.query.filterParams)
  }
})

const getEquipmentName = (key) => {
  return equipmentNames[key] || key
}

const getStatusName = (status) => {
  return statusNames[status] || status
}

const getStatusType = (status) => {
  return statusTypes[status] || ''
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledHours = () => {
  return [...Array(24).keys()].filter(h => h < 8 || h >= 21)
}

const disabledMinutes = (hour) => {
  if (hour === 20) {
    return [...Array(60).keys()].filter(m => m > 0)
  }
  return []
}

// 刷新会议室数据
const refreshRooms = async () => {
  loading.value = true
  try {
    if (Object.keys(filterParams.value).length > 0) {
      rooms.value = await filterRooms(filterParams.value)
    } else {
      // 如果没有筛选参数，可以调用获取全部会议室的API
      // rooms.value = await getRooms()
      ElMessage.warning('请先进行筛选')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('获取最新会议室数据失败')
  } finally {
    loading.value = false
  }
}

const handleBook = (room) => {
  bookingForm.value = {
    room_id: room.room_id,
    room_name: room.room_name,
    start_time: '',
    end_time: '',
    total_price: 0
  }
  dialogVisible.value = true
}

const calculatePrice = () => {
  if (!bookingForm.value.start_time || !bookingForm.value.end_time) {
    bookingForm.value.total_price = 0
    return
  }
  
  const hours = (bookingForm.value.end_time - bookingForm.value.start_time) / (1000 * 60 * 60)
  const room = rooms.value.find(r => r.room_id === bookingForm.value.room_id)
  
  if (room && hours > 0) {
    bookingForm.value.total_price = Math.round(room.price * hours * 100) / 100
  } else {
    bookingForm.value.total_price = 0
  }
}

watch(() => [bookingForm.value.start_time, bookingForm.value.end_time], () => {
  calculatePrice()
})

const handleConfirm = async () => {
  if (!bookingForm.value.start_time || !bookingForm.value.end_time) {
    ElMessage.warning('请选择开始时间和结束时间')
    return
  }
  
  if (bookingForm.value.total_price <= 0) {
    ElMessage.warning('请选择有效的时间段')
    return
  }
  
  bookingLoading.value = true
  try {
    const userId = authStore.getUserId
    const order = {
      room_id: bookingForm.value.room_id,
      start_time: bookingForm.value.start_time.toISOString(),
      end_time: bookingForm.value.end_time.toISOString(),
      total_price: bookingForm.value.total_price,
      userId
    }
    
    await createOrder(order)
    ElMessage.success('预订成功，请在30分钟内完成支付')
    
    // 预订成功后刷新数据
    await refreshRooms()
    dialogVisible.value = false
  } catch (error) {
    console.error('预订失败:', error)
    ElMessage.error(error.response?.data?.error || '预订失败')
  } finally {
    bookingLoading.value = false
  }
}
</script>

<style scoped>
.room-list-container {
  padding: 20px;
}

.mr-2 {
  margin-right: 8px;
}

.refresh-btn {
  margin-bottom: 20px;
}
</style>